import axios from 'axios'
import {
    ElMessage
} from 'element-plus'

import {
    getJWTToken,removeJWTToken,setJWTToken
} from "@/utils/tokens"

import router from '@/router/index'


const service = axios.create({
    baseURL: "", // api 的 base_url
    withCredentials: true,
    timeout: 30 * 1000 // 默认最长时间30秒
})

// 拦截器
service.interceptors.request.use(
    (    config: any) => {
        // Do something before request is sent
        // if (store.getters.token) {
        //     // 让每个请求携带token-- ['X-Token']为自定义key 请根据实际情况自行修改
        //     config.headers['X-Token'] = getToken()
        // }
        let jwtToken = getJWTToken();

        if (jwtToken) {
            config.headers["Authorization"] = "Bearer " + jwtToken;
        }

        return config
    },
    (    error: any) => {
        // Do something with request error
        console.log(error) // for debug
        Promise.reject(error)
    }
)

service.interceptors.response.use(
    (   
    response: { data: { code: number; success: boolean; message: string; data: any;jwt:string} }) => {
        // console.log("data",response);
        if(response.data.jwt){
            setJWTToken(response.data.jwt);
        }

        // 请求成功返回
        if (response.data.success) {
            return Promise.resolve(response.data.data);
        } 

        // 请求响应失败逻辑
        else {
            // 登录状态过期
            if(response.data.code == 19000){
                ElMessage({
                    message: "登陆失败！",
                    type: 'error',
                    duration: 3 * 1000
                })

                // 清理 cookie
                removeJWTToken();

                router.push("/pages/login");
                return Promise.reject(response.data.message);;
            }

            else if (response.data.code == 19500){
                ElMessage({
                    message: "注销成功",
                    type: 'success',
                    duration: 3 * 1000
                })

                removeJWTToken();

                router.push("/pages/login");

                return Promise.resolve(response.data.message);;
            }

            // 通用返回错误处理
            else {
                ElMessage({
                    message: response.data.message,
                    type: 'error',
                    duration: 3 * 1000
                })
    
                return Promise.reject(response.data.message);;
            }
        }
    },
    ( error: any) => {
        if (axios.isCancel(error)) {
            console.log("已经取消");
        } else {
            ElMessage({
                message: "服务器错误",
                type: 'error',
                duration: 3 * 1000
            })

            console.log("error",error)

            return Promise.reject(error)
        }
    }
)



export default service